<template>
  <div class="dashboard-container">
    <div class="app-container">
      <Page-tools :show-before="false">
        <template v-slot:before>
          左侧自定义
        </template>
        <template v-slot:after>
          <el-button type="primary" size="mini" @click="$router.push('/import')">导入</el-button>
          <el-button type="primary" size="mini" @click="onExcelExport">导出</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="showDialog = true">新增员工</el-button>
        </template>
      </Page-tools>

      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" sortable />
          <el-table-column label="姓名" prop="username" sortable />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <img
                v-imgError="require('../../assets/common/bigUserHeader.png')"
                class="avatar"
                :src="scope.row.staffPhoto"
                @click="onClickAvatar(scope.row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" sortable>
            <template slot-scope="scope">
              {{ scope.row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable>
            <template slot-scope="scope">
              {{ scope.row.enableState ? '可用' : '不可用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" :disabled="checkPermission(points.pointUserUpdate)" @click="$router.push('/employees/' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small" :disabled="checkPermission(points.pointUserSetJob)">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="onClickRole(scope.row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="checkPermission(points.pointUserDelete)" @click="onClickDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" />
        </el-row>
      </el-card>

      <!-- 新增员工 -->
      <AddEmployees :show-dialog.sync="showDialog" @add-success="getEmployeeList()" />
    </div>
    <!-- 绘制二维码 -->
    <el-dialog class="qrcode" title="二维码" :visible.sync="dialogVisible">
      <canvas id="qrcode" />
    </el-dialog>

    <!-- 角色分配权限 -->
    <AssignRole v-if="setRoleDialog" :set-role-dialog.sync="setRoleDialog" :current-employees-id="currentEmployeesId" />
  </div>
</template>

<script>
import { getEmployeesList, deleteEmployees } from '@/api/employees'
import AddEmployees from './components/Add-employees.vue'
import { formatHireType } from '@/filters'
import { formatDate } from '@/utils'
import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
import permissionMix from '@/mixins/permission'
export default {
  name: 'Employees',
  components: {
    AddEmployees,
    AssignRole
  },
  mixins: [permissionMix],
  data() {
    return {
      tablePage: {
        page: 1,
        size: 10
      },
      total: 0,
      employeeList: [],
      showDialog: false,
      dialogVisible: false,
      setRoleDialog: false,
      currentEmployeesId: ''
    }
  },

  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const res = await getEmployeesList(this.tablePage)
      this.total = res.total
      this.employeeList = res.rows
    },
    handleCurrentChange(val) {
      this.tablePage.page = val
      this.getEmployeeList()
    },
    onClickDel(row) {
      console.log(row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteEmployees(row.id)
        this.getEmployeeList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {})
    },
    onExcelExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // const res = await getEmployeesList({ page: 1, size: this.total })
        // console.log(res)
        const res = await getEmployeesList({ page: 1, size: this.total })
        const mapKey = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const tHeader = Object.keys(mapKey)
        const arr = this.formatExcelData(res.rows, tHeader, mapKey)
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data: arr, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    formatExcelData(data, tHeader, mapKey) {
      return data.map(item => {
        return tHeader.map(headerItem => {
          if ((item[mapKey[headerItem]] - 0) > 0 && (headerItem === '入职日期' || headerItem === '转正日期')) {
            return formatDate(item[mapKey[headerItem]], '-')
          } else if (headerItem === '聘用形式') {
            formatHireType(item[mapKey[headerItem]])
          }
          return item[mapKey[headerItem]]
        })
      })
    },
    onClickAvatar(url) {
      this.dialogVisible = true
      if (url) {
        this.$nextTick(() => {
          const canvas = document.getElementById('qrcode')
          QRCode.toCanvas(canvas, url, function(error) {
            if (error) this.$message.error('生成失败')
          })
        })
      } else {
        this.$message.error('获取图片失败')
      }
    },
    onClickRole(userId) {
      this.setRoleDialog = true
      this.currentEmployeesId = userId
    }

  }

}
</script>

<style scoped lang='scss'>
  .avatar{
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
  ::v-deep .qrcode .el-dialog__body{
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
